package com.gem.shop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhang
 * @date 2020/9/19 10:22
 *
 */
@WebFilter(urlPatterns = "/*",initParams = {
        @WebInitParam(name = "encoding",value = "UTF-8")
})
public class CharacterEncodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        //设置相应字符集
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        //放行
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
